const sqlite3 = require('sqlite3').verbose();
const run=function(query) {
    return new Promise(function(resolve, reject) {
        conn.run(query,
            function(err)  {
                if(err) reject(err.message)
                else    resolve(true)
        })
    })   
}
function selectPassword(service, account,callback) {
    return new Promise(function(resolve, reject) {
        let cmd=`select * from pwd where service='${service}' and account='${account}'` ;
        // console.log(cmd);
        conn.get(cmd,(err, row)=>{
            // console.log("err:", err,"row:",row)
            if(err!==null){
                reject(err);
            }else{
                resolve(row)
            }
        });

    })
}
async function setPassword(service, account,password) {
    let r=await selectPassword(service,account)
    if(r){//find
        updatePassword(service, account,password)
    }else{
        createPassword(service, account,password)
    }
}
async function createPassword(service, account,password) {
    let cmd=`insert into pwd(service,account,password) values('${service}','${account}','${password}')` ;
    await run(cmd)
}
async function updatePassword(service, account,password) {
    console.log("updatePassword")
    let cmd=`update pwd set password='${password}' where service='${service}' and account='${account}'` ;
    console.log(cmd)
    await run(password,service,account).catch((e)=>{
        console.log(e);
    });
}
async function createTable() {
    let r=await run("CREATE TABLE pwd (service TEXT, account TEXT, password TEXT, PRIMARY KEY (service, account))").catch((e)=>{
        console.log(e);
    })
}
function selectAccount(service,callback) {
    return new Promise(function(resolve, reject) {
        let cmd=`select * from pwd where service='${service}'` ;
        console.log(cmd);
        conn.all(cmd,(err, row)=>{
            console.log("err:", err,"row:",row)
            if(err!==null){
                reject(err);
            }else{
                resolve(row)
            }
        });
    })
}
let filename=__dirname+"/key.sqlite"
let conn = new sqlite3.Database(filename);
async function main(){
    // await createTable();
    // setPassword("localhost",'mahongquan','233333')
    const r=await updatePassword("localhost",'mahongquan','333')
    // let r=await selectAccount("localhost")
    // console.log(r)
}
// createTable()
main()
// module.expors={selectAccount,createTable,setPassword,selectPassword}
